﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using WpfCanvas.Contour;

namespace WpfCanvas
{
	/// <summary>
	/// BMP.xaml 的交互逻辑
	/// </summary>
	public partial class BMP : Window
	{
		public BMP()
		{
			InitializeComponent();
		}

		public static string[] colors = { "006837", "1a9850", "66bd63", "a6d96a", "d9ef8b", "ffffbf", "fee08b", "fdae61", "f46d43", "d73027", "a50026" };

		private ReadInTemp ReadInData { get; set; }

		public byte[] GetPictureData(string imagepath)
		{
			FileStream fs = new FileStream(imagepath, FileMode.Open);
			byte[] byData = new byte[fs.Length];
			fs.Read(byData, 0, byData.Length);
			fs.Close();
			return byData;
		}
			
		private void CButton_Click(object sender, RoutedEventArgs e)
		{
			
			OpenFileDialog ofd = new OpenFileDialog();
			if (ofd.ShowDialog() == true)
			{
				String fileName = ofd.FileName;
				var rawdatas = OpenResultCSVFile(fileName);

				ReadInData = ParseSurfaceRawData(rawdatas, 100, 100);

				double zMin = ReadInData.Min;
				double zMax = ReadInData.Max;

				Bitmap bm = new Bitmap(100, 100);
				for (int i = 0; i < 100; i++)
				{
					for (int j = 0; j < 100; j++)
					{
						double ptelement = ReadInData.RawData[i][j];
						double z = ((ptelement - zMin) / (zMax - zMin));

						if (z < 0.0) z = 0.0;
						if (z > 1) z = 1;


                        int indexColor = (int)Math.Floor((colors.Length - 1) * z);
                        System.Drawing.Color clr = HexToColor(colors[indexColor]);
                        bm.SetPixel(i,j, clr);
                    }
				}
				BitmapImage bitmapImage = new BitmapImage();
				bitmapImage = BitmapToBitmapImage(bm);
							
				var gridheight = imgGrid.ActualHeight;
                var gridwidth = imgGrid.ActualWidth;
				
				var size=gridheight / 2;
                if (gridheight > gridwidth)
                {
					size = gridwidth / 2;
                }
                
                origImage.Source = bitmapImage;

                
                EllipseGeometry clipGeometry = new EllipseGeometry(new System.Windows.Point(size , size ), size , size );
                origImage.Clip = clipGeometry;
            }
        }

		public BitmapImage BitmapToBitmapImage(Bitmap bitmap)
		{
			Bitmap bitmapSource = new Bitmap(bitmap.Width, bitmap.Height);
			int i, j;
			for (i = 0; i < bitmap.Width; i++)
				for (j = 0; j < bitmap.Height; j++)
				{
					System.Drawing.Color pixelColor = bitmap.GetPixel(i, j);
					System.Drawing.Color newColor = System.Drawing.Color.FromArgb(pixelColor.R, pixelColor.G, pixelColor.B);
					bitmapSource.SetPixel(i, j, newColor);
				}
			MemoryStream ms = new MemoryStream();
			bitmapSource.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
			BitmapImage bitmapImage = new BitmapImage();
			bitmapImage.BeginInit();
			bitmapImage.StreamSource = new MemoryStream(ms.ToArray());
			bitmapImage.EndInit();

			return bitmapImage;
		}
		private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
		{
		

			var height = origImage.ActualHeight;
            var width = origImage.ActualWidth;

            EllipseGeometry clipGeometry = new EllipseGeometry(new System.Windows.Point(height / 2, width / 2), height / 2, width / 2);
            origImage.Clip = clipGeometry;

        }

        public double[,] OpenResultCSVFile(string filePath)
		{

			double[,] ret = new double[101, 101];
			//double[][] rets = new double[101][];

			Encoding encoding = Encoding.ASCII;//

			FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);

			//StreamReader sr = new StreamReader(fs, Encoding.UTF8);
			StreamReader sr = new StreamReader(fs, encoding);
			//string fileContent = sr.ReadToEnd();
			//encoding = sr.CurrentEncoding;
			//记录每次读取的一行记录
			string strLine = "";
			//记录每行记录中的各字段内容
			string[] aryLine = null;
			string[] tableHead = null;
			//标示列数
			int columnCount = 0;
			//标示是否是读取的第一行
			bool IsFirst = true;
			//逐行读取CSV中的数据


			double max = -100000;
			double min = 100000;

			Dictionary<string, int> elementCount = new Dictionary<string, int>();

			SortedDictionary<int, int> ValueCount = new SortedDictionary<int, int>();



			int xIndex = 0;
			while ((strLine = sr.ReadLine()) != null)
			{
				aryLine = strLine.Split(',');

				//rets[xIndex] = new double[101];

				for (int yIndex = 0; yIndex < 101; yIndex++)
				{
					if (String.IsNullOrEmpty(aryLine[yIndex]))
						break;

					double zValueIn = double.Parse(aryLine[yIndex]);


					ret[xIndex, yIndex] = zValueIn;
				}

				xIndex++;
				if (xIndex == 101)
					break;
			}
			sr.Close();
			fs.Close();

			return ret;
		}

		public ReadInTemp ParseSurfaceRawData(double[,] rawdata, int width, int height)
		{
			double[][] rets = new double[height][];


			double max = -100000;
			double min = 100000;

			Dictionary<string, int> elementCount = new Dictionary<string, int>();

			SortedDictionary<int, int> ValueCount = new SortedDictionary<int, int>();

			double[] arrayRawDatas = new double[width * height];
			int arrayIndex = 0;

			int xIndex = 0;
			for (int row = 0; row < height; row++)
			{


				rets[xIndex] = new double[width];

				for (int yIndex = 0; yIndex < width; yIndex++)
				{
					double zValueIn = rawdata[row, yIndex];

					arrayRawDatas[arrayIndex++] = zValueIn;

					//注意平均值
					// int zValue =  (int)((zValueIn - AverageValue) * 1000);

					int zValue = (int)((zValueIn) * 100000);

					rets[xIndex][yIndex] = zValue;

					if (ValueCount.ContainsKey(zValue))
					{
						ValueCount[zValue]++;
					}
					else
					{
						ValueCount.Add(zValue, 1);
					}

					String key = zValue.ToString("f2");

					if (elementCount.ContainsKey(key))
					{
						elementCount[key]++;
					}
					else
					{
						elementCount.Add(key, 1);
					}

					if (zValue > max)
					{
						max = zValue;
					}

					if (zValue < min)
					{
						min = zValue;
					}
				}

				xIndex++;

			}

			string whoIsMax = "0";
			int whoIsMaxValue = -10000;

			foreach (var item in elementCount)
			{
				if (item.Value > whoIsMaxValue)
				{
					whoIsMax = item.Key;
				}
			}

			ReadInTemp retTemp = new ReadInTemp();
			retTemp.RawData = rets;
			retTemp.RawDataArray = arrayRawDatas;
			retTemp.Max = max;
			retTemp.Min = min;
			retTemp.Mid = double.Parse(whoIsMax);

			retTemp.W = width;
			retTemp.H = height;

			retTemp.ValueCount = ValueCount;

			return retTemp;
		}

		public static System.Drawing.Color HexToColor(string hex)
		{
			byte br = byte.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
			byte bg = byte.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
			byte bb = byte.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
			//byte cc = byte.Parse(hex.Substring(6, 2), System.Globalization.NumberStyles.HexNumber);
			int r = br;
			int g = bg;
			int b = bb;
			//int a = cc / 255;
			return System.Drawing.Color.FromArgb(br, bg, bb);
		}
	}
}
